//
//  BuyPigViewController.m
//  PigMarket
//
//  Created by mac on 2019/4/10.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "BuyPigViewController.h"
#import "BuyPigCell.h"
#import "AdoptBugCell.h"
#import "PigPayFooterView.h"
#import "PayViewController.h"
#import "PigTrusteePriceView.h"
#import "SelectDiscountCouponsView.h"

#import "BugPigBox.h"
#import "UndoptPayViewController.h"

@interface BuyPigViewController ()

@property (nonatomic, strong) UIView *tipView;
@property (nonatomic, strong) PigPayFooterView *footerView;

/**
 优惠券价格
 */
@property (nonatomic, strong) NSString *selectTrusteePrice;

/**
 猪价格
 */
@property (nonatomic, strong) NSString *pigPrice;

/**
实付价格
 */
@property (nonatomic, strong) NSString *owedPaymentMoney;


/**
 应付价格
 */
@property (nonatomic, strong) NSString *actuallyPaymentMoney;


/**
 优惠券提示价格 -¥10
 */
@property (nonatomic, strong) NSString *discountMoney;


/**
 优惠券计算价格
 */
@property (nonatomic, strong) NSNumber *discountPrice;


/**
 优惠券有无提示
 */
@property (nonatomic, strong) NSString *discountTips;

@property (nonatomic, strong) AdoptDetail *youhuiItem;
@property (nonatomic, strong) AdoptDetail *totalItem;
@property (nonatomic, strong) AdoptDetail *pigItem;

@property (nonatomic, strong) NSMutableArray *discountCouposArr;
@property (nonatomic, strong) NSMutableArray *discountCouposIdArr;
@property (nonatomic, strong) NSMutableArray *datas;
@property (nonatomic, strong) NSArray *titles;
@property (nonatomic, strong) NSArray *details;



@end

@implementation BuyPigViewController

#pragma mark - init method
- (void)setupUI {
    self.baseNavView.navTitleLabel.text = @"仔猪购买";
    [self.view addSubview:self.footerView];
    
    self.discountMoney = @"";
    
    [self initAction];
    [self initData];
}


- (void) setupLayout {
    
    [self.footerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.height.mas_equalTo(54+TJ_SafeAreaBottomHeight);
    }];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.mas_equalTo(TJ_NavBarHeight);
        make.bottom.mas_equalTo(self.footerView.mas_top);
    }];
}


- (void) initAction {
    //保存数值，区分小猪托管费用  仔猪是否默认选择
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    [user setValue:@"YES" forKey:@"pigTrusteeIsSelect"];
    }


- (void)initData {
    //获取豚券
    [self discountCouponsRequest];

    //加载数据
    [self refreshData];
}

//获取豚券请求
- (void)discountCouponsRequest {
    
    NSNumber *memberId = [UserInfoDataProvider sharedInstance].userInfo.memberId;
    DiscountCouponsParam *param = [[DiscountCouponsParam alloc] init];
    param.page = 1;
    param.limit = 50;
    param.memberId = memberId;
    param.type = @1;
    
    @weakify(self);
    [[[PigMarketApi sharedInstance] userDiscountCouponsWithParam:param] subscribeNext:^(DiscountCouponsList * _Nullable discountCouponsList) {
        @strongify(self);
        
        [self.discountCouposArr addObjectsFromArray:discountCouponsList.list];
        
        if (self.discountCouposArr.count == 0) {
            self.discountTips = @"无可用豚券";
        } else {
            self.discountTips = @"有可用豚券";
        }
        [self refreshData];
        [self.tableView reloadData];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
    }];
}

- (void)refreshData {
    
    {
        [self.datas removeAllObjects];
        
        [self.datas addObjectsFromArray:self.detailModel.stagePrices];
        self.pigItem = [self.datas firstObject];
        [self.datas removeObjectAtIndex:0];
        
        self.youhuiItem = [self.datas lastObject];
        [self.datas removeLastObject];
        
        self.totalItem = [self.datas lastObject];
        [self.datas removeLastObject];

    }
    
    
    {
        self.pigPrice = self.pigItem.money;
        
        self.discountTips = self.discountTips ? self.discountTips : @"";
        NSString *pigPrice = [NSString stringWithFormat:@"¥%@", self.pigItem.money];
        NSString *wholePrice = [NSString stringWithFormat:@"¥%@", self.youhuiItem.money];
        
        NSMutableAttributedString *text1 = [@"" createAttributingByIcon:nil downIndexImage:nil textColor:UIColorFromRGB(0x262626) font:mFont(14)];
        NSMutableAttributedString *text2 = [pigPrice createAttributingByIcon:nil downIndexImage:nil textColor:UIColorFromRGB(0x666666) font:mFont(12)];
        NSMutableAttributedString *text3 = [wholePrice createAttributingByIcon:nil downIndexImage:nil textColor:UIColorFromRGB(0x666666) font:mFont(12)];
        NSMutableAttributedString *text4 = [self.discountMoney createAttributingByIcon:nil downIndexImage:nil textColor:UIColorFromRGB(0xF25C62) font:mFont(12)];
        NSMutableAttributedString *text5 = [self.discountTips createAttributingByIcon:nil downIndexImage:@"meat_cart_enter" textColor:UIColorFromRGB(0x999999) font:mFont(12)];
        
        _details =  @[text1, text2, text3, text4, text5];

    }
    
    
    {
        //优惠价钱
        if ([JTool iSNull:self.discountMoney]) {//如果为空 默认赋值为0
            self.discountMoney = @"0";
        }
        NSString *discount = [NSString stringWithFormat:@"(已优惠%@元)",self.discountMoney];
        NSDictionary *dic = @{@"title":@"实付款",
                              @"discount":discount,
                              @"confirmTitle":@"立即支付"
                               };
        self.footerView.infoDic = dic;
        
        //应付价格
        float startPayPrice = [self.pigPrice floatValue] + [self.selectTrusteePrice floatValue];
        self.actuallyPaymentMoney = [NSString stringWithFormat:@"%.2f", startPayPrice];
        
        float endPayPrice = [self.pigPrice floatValue] + [self.selectTrusteePrice floatValue] - [self.discountPrice floatValue];
        if (endPayPrice < 0) {
            endPayPrice = 0.00;
        }
        
        self.footerView.priceLab.text = [NSString stringWithFormat:@"￥%.2f",endPayPrice];
        //应付款 = 猪的价钱 + 阶段费用
        self.owedPaymentMoney = [NSString stringWithFormat:@"%.2f", endPayPrice];

    }
}


#pragma mark - delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return section == 0 ?3 :5;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        if (indexPath.row == 1) return 140;
        
        if(indexPath.row == 2){
            
            int count = (int)self.datas.count / 3;
            if (self.datas.count % 3 > 0) {
                count += 1;
            }
            return 120 * count + 50;
        }
    }
    
    return 50;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if (indexPath.section == 0) {
        
        if (indexPath.row == 1) {
            AdoptBugCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AdoptBugCell"];
            cell.item = self.youhuiItem;
            
            return cell;
        }
        
        if (indexPath.row == 2) {
            
            if (self.datas.count > 0) {
                TrusteeCell *cell = [TrusteeCell cellWithTrusteeTableView:tableView];
                [cell configCellWithDataArr:self.datas type:TrusteeTypeUnAdopted];
                return cell;
            }
        }
    }
        
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"UITableViewCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

    }
    
    if (indexPath.section == 0 && indexPath.row == 0) {
        
        NSString *text = @"托管阶段 可多选";
        NSMutableAttributedString *aims = [[NSMutableAttributedString alloc] initWithString:text];
        [aims addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0x262626) range:NSMakeRange(0, 4)];
        [aims addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0x999999) range:NSMakeRange(5, 3)];
        [aims addAttribute:NSFontAttributeName value:mFont(15) range:NSMakeRange(0, 4)];
        [aims addAttribute:NSFontAttributeName value:mFont(12) range:NSMakeRange(5, 3)];
        cell.textLabel.attributedText = aims;
        
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%@个", @(self.datas.count)];
        cell.detailTextLabel.textColor = UIColorFromRGB(0x999999);
        cell.detailTextLabel.font = mFont(13);
    }else{
        
        cell.textLabel.attributedText = self.titles[indexPath.row];
        cell.detailTextLabel.attributedText = self.details[indexPath.row];
    }
    
 return cell;

}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0 && indexPath.row ==1) {
        
        self.youhuiItem.isSelect = !self.youhuiItem.isSelect;
        
        if (self.youhuiItem.isSelect) {
            float aims = [self.youhuiItem.money floatValue] - [self.pigItem.money floatValue];
            self.selectTrusteePrice = [NSString stringWithFormat:@"%.2f", aims] ;
        }else{
            self.selectTrusteePrice =  [NSString stringWithFormat:@"-%@", self.pigItem.money]  ;
        }
        
        [self refreshData];
        [self localReloadTableViewBySection:0];
        
        [kNotificationCenter postNotificationName:NotificationTrusteePriceWhole object:@(self.youhuiItem.isSelect)];
        
    }

    if (indexPath.section == 1 && indexPath.row == 4) {
        if (self.discountCouposArr.count == 0) {
            [self toastWithContent:@"您无可用豚券"];
            return;
        } else {
            BugPigBox *box = [[BugPigBox alloc] init];
            box.datas = self.discountCouposArr;
            
            @weakify(self);
            box.selectBlock = ^(DiscountCoupons * _Nonnull item) {
                @strongify(self);
                
                if (item) {
                    
                    if ([item.couponValue integerValue] == 0) {
                        self.discountMoney = [NSString stringWithFormat:@"￥%@",item.couponValue];
                    } else {
                        self.discountMoney = [NSString stringWithFormat:@"￥-%@",item.couponValue];
                    }
                    
                    [self.discountCouposIdArr removeAllObjects];
                    [self.discountCouposIdArr addObject:item.meCouponId];
                    self.discountPrice = item.couponValue;
                    
                    [self refreshData];
                    [self.tableView reloadData];

                }else{
                   
                    [self.discountCouposIdArr removeAllObjects];
                    self.discountMoney = @"¥0";
                    self.discountPrice = @(0.00);
                    [self refreshData];
                    [self.tableView reloadData];
                }
            };
            
            [box showView];
        }
    }
}


//立即支付
- (void)payTapped {
    //添加必须选择仔猪和一个套餐
    if (!([self.selectTrusteePrice floatValue] > 0)) {
        [self toastWithContent:@"请选择阶段托管费用"];
        return;
    }
    
    UndoptPayViewController *payVC = [[UndoptPayViewController alloc] init];
    payVC.model = self.detailModel;
    payVC.actuallyPaymentMoney = self.actuallyPaymentMoney;
    payVC.owedPaymentMoney = self.owedPaymentMoney;
    payVC.adoptType = UnAdoptTypeBuy;
    payVC.discountMoney = self.discountMoney;
    payVC.discountMoneyIdArr = self.discountCouposIdArr;
    [self.navigationController pushViewController:payVC animated:YES];
}


#pragma mark - getter and setter

- (void)registerTableViewCell{
    
    self.tableView.rowHeight = 42;
    self.tableView.mj_footer.hidden = YES;
    self.tableView.mj_header.hidden = YES;
    self.tableView.separatorColor = mIconLineColor;
    self.tableView.tableFooterView = self.tipView;
    [self.tableView registerClass:[AdoptBugCell class] forCellReuseIdentifier:@"AdoptBugCell"];
}


- (PigPayFooterView *)footerView {
    if (!_footerView) {
        _footerView = [[PigPayFooterView alloc] init];
        [_footerView.confirmBtn addTarget:self action:@selector(payTapped) forControlEvents:UIControlEventTouchUpInside];
        _footerView.backgroundColor = [UIColor whiteColor];
        _footerView.frame = CGRectMake(0, 10, KScreenWidth, 54 +TJ_SafeAreaBottomHeight);
    }
    return _footerView;
}

- (UIView *)tipView {
    
    if (!_tipView) {
        _tipView = [UIView new];
        _tipView.backgroundColor = UIColorFromRGB(0xFFF9D4);
        _tipView.frame = CGRectMake(0, 0, KScreenWidth, 34);
        
        UILabel *titlelab = [UILabel makeLabelWithText:@"该仔猪保险由自然生长信息（天津）技术有限公司提供" textColor:UIColorFromRGB(0xEC8C00) font:mFont(12) textAliment:0];
        titlelab.frame = CGRectMake(15, 0, KScreenWidth - 87, 34);
        [_tipView addSubview:titlelab];
        
        
        UILabel *tiplab = [UILabel makeLabelWithText:@"详情查看" textColor:UIColorFromRGB(0xF25C62) font:mFont(12) textAliment:0];
        tiplab.frame = CGRectMake(titlelab.right + 8, 0, 60, 34);
        
        tiplab.tapBlock = ^{
            
            [self showHudWithMsg:@"详情查看"];
        };
        [_tipView addSubview:tiplab];
        
    }
    return _tipView;
}


- (NSArray *)titles{
    
    if (!_titles) {
        
        NSMutableAttributedString *text1 = [@"结算信息" createAttributingByIcon:nil downIndexImage:nil textColor:UIColorFromRGB(0x262626) font:mFont(14)];
        NSMutableAttributedString *text2 = [@"仔猪价格" createAttributingByIcon:nil downIndexImage:nil textColor:UIColorFromRGB(0x262626) font:mFont(14)];
        NSMutableAttributedString *text3 = [@"全包价格" createAttributingByIcon:nil downIndexImage:nil textColor:UIColorFromRGB(0x262626) font:mFont(14)];
        NSMutableAttributedString *text4 = [@"  折扣" createAttributingByIcon:@"pay_zhe" downIndexImage:nil textColor:UIColorFromRGB(0x262626) font:mFont(14)];
        NSMutableAttributedString *text5 = [@"  豚券" createAttributingByIcon:@"pay_quan" downIndexImage:nil textColor:UIColorFromRGB(0x262626) font:mFont(14)];
        _titles = @[text1, text2, text3, text4, text5];
    }
    return _titles;
}

- (NSMutableArray *)datas {
    if (!_datas) {
        _datas = [[NSMutableArray alloc] init];
    }
    return _datas;
}


- (NSMutableArray *)discountCouposArr {
    if (!_discountCouposArr) {
        _discountCouposArr = [[NSMutableArray alloc] init];
    }
    return _discountCouposArr;
}


- (NSMutableArray *)discountCouposIdArr {
    if (!_discountCouposIdArr) {
        _discountCouposIdArr = [[NSMutableArray alloc] init];
    }
    return _discountCouposIdArr;
}



#pragma mark - notifications methods
- (void)addNotifications{

    [kNotificationCenter addObserver:self selector:@selector(selectTrusteePriceNot:) name:NotificationTrusteePriceChange object:nil];

}

- (void)removeNotifications{
    
    [kNotificationCenter removeObserver:self name:NotificationTrusteePriceChange object:nil];
}

//选择完套餐 刷新页面数据显示
- (void)selectTrusteePriceNot: (NSNotification *)notification {
    NSDictionary *dic = notification.userInfo;
    NSNumber *number = dic[@"isWhole"];
    
    self.youhuiItem.isSelect = [number integerValue] == 1 ? YES :NO;
    
    float price =[dic[@"selectTrusteePrice"] floatValue];
    float youhuiPrice = [self.youhuiItem.discountPrice floatValue];
    float aims = [number integerValue] == 1 ?(price - youhuiPrice) :price;
    self.selectTrusteePrice = [NSString stringWithFormat:@"%.2f", aims];
    
    NSLog( @"__________  %lf  %@",price,  self.selectTrusteePrice);
    
    [self refreshData];
    [self.tableView reloadData];
}


@end
